package impl

import (
	"time"
	"ylb/entity"
	"ylb/mapper"
)

type JobServiceImpl struct {
	mapper mapper.JobMapper
}

func NewJobServiceImpl() JobServiceImpl {
	service := JobServiceImpl{}
	service.mapper = mapper.NewJobMapper()
	return service
}

func (j JobServiceImpl) SelectAll(u uint) []entity.Job {

	return j.mapper.SelectAllByUserId(u)
}

func (j JobServiceImpl) SelectAllByDayExpire(userId uint, limitDay int) []entity.Job {
	var now time.Time
	var tomorrow time.Time
	//正数代表未来天数
	if limitDay >= 0 {
		now = time.Now()
		//获取当前时间
		increDay := (limitDay + 1) * 24
		add := now.Add(time.Duration(increDay) * time.Hour)
		year, month, day := add.Date()
		//今天24:0:0结束
		tomorrow = time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
	} else {
		//负数代表已过期天数

		tomorrow = time.Now()
		increDay := (limitDay) * 24
		add := tomorrow.Add(time.Duration(increDay) * time.Hour)
		year, month, day := add.Date()
		//今天24:0:0结束
		now = time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
	}

	return j.mapper.SelectAllByLimitTime(userId, now, tomorrow)
}
func (j JobServiceImpl) SelectAllByCollect(userId uint) []entity.Job {
	return j.mapper.SelectAllByCollect(userId)
}

func (j JobServiceImpl) CollectJob(jobId int, collect bool) int64 {

	return j.mapper.UpdateJob(jobId, map[string]interface{}{
		"collect": collect,
	})
}
func (j JobServiceImpl) SelectAllByClassify(userId uint, classify uint) []entity.Job {

	return j.mapper.SelectAllByClassifyAndUserId(userId, classify)
}

func (j JobServiceImpl) SelectAllByLike(like string) []entity.Job {
	if like == "" {
		return nil
	}
	return j.mapper.SelectAllByLike(like)
}

func (j JobServiceImpl) Insert(job *entity.Job) int64 {

	return j.mapper.InsertOne(job)
}

func (j JobServiceImpl) Delete(id uint) int64 {

	return j.mapper.DeleteOne(id)
}

//参数:day,hour,min,sec,method(0 过期 / 1 未过期)
func (j JobServiceImpl) SelectAllByWhere(userId uint, m map[string]int) []entity.Job {
	var now time.Time
	var tomorrow time.Time

	method := m["method"]
	day := m["day"]
	hour := m["hour"]
	min := m["min"]
	sec := m["sec"]

	//计算秒数

	allTime := day*24*3600 + hour*3600 + min*60 + sec

	//过期
	if method == 0 {
		tomorrow = time.Now()
		now = tomorrow.Add(time.Duration(-1*allTime) * time.Second)
	} else {
		now = time.Now()
		tomorrow = now.Add(time.Duration(allTime) * time.Second)
	}

	return j.mapper.SelectAllByLimitTime(userId, now, tomorrow)
}
